package com.etung.iot.demo.handler;

import com.alibaba.fastjson.JSONObject;
import com.etung.iot.demo.configs.TopicConfig;
import com.etung.iot.demo.dao.GateWayMapper;
import com.etung.iot.demo.modles.GateWayInfo;
import com.etung.iot.demo.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Component
@Handler(TopicConfig.COLLECTOR_INFO_TOPIC)
@Slf4j
public class CollectorInfoHandler implements TopicHandler{

    @Autowired
    private GateWayMapper gateWayMapper;

    @Override
    public void handler(String topic,String payload) {
        log.info("payload:"+payload);
        JSONObject jsonObject = JSONObject.parseObject(payload);
        GateWayInfo gatewayInfo = new GateWayInfo();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            if("version".equals(entry.getKey())){
                gatewayInfo.setVersion(entry.getValue().toString());
            }else if("imei".equals(entry.getKey())){
                gatewayInfo.setImei(entry.getValue().toString());
            }else if("phonenumber".equals(entry.getKey())){
                gatewayInfo.setPhonenumber(entry.getValue().toString());
            }else if("quality".equals(entry.getKey())){
                gatewayInfo.setQuality(entry.getValue().toString());
            }else if("modifyTime".equals(entry.getKey())){
                if(!StringUtils.isEmpty(entry.getValue().toString())){
                    gatewayInfo.setModifyTime(sdf.format(new Date(Long.parseLong(entry.getValue().toString()) * 1000)));
                }
            }else if ("deviceName".equals(entry.getKey())){
                gatewayInfo.setName(entry.getValue().toString());
            }else if("simcard".equals(entry.getKey())){
                gatewayInfo.setSimcard(entry.getValue().toString());
            }else if("modnet".equals(entry.getKey())){
                gatewayInfo.setModnet(entry.getValue().toString());
            }
        }
        if(!StringUtils.isEmpty(gatewayInfo.getImei())){
            gatewayInfo.setTime(new Date(System.currentTimeMillis()));
            gateWayMapper.insert(gatewayInfo);
        }
    }
}
